package com.wjj.sixinone.service.impl;

import com.wjj.sixinone.common.enums.ExceptionEnum;
import com.wjj.sixinone.common.enums.StatusEnum;
import com.wjj.sixinone.common.exception.GlobalException;
import com.wjj.sixinone.common.pojo.dto.Dashboard;
import com.wjj.sixinone.common.pojo.dto.PieDataDTO;
import com.wjj.sixinone.common.pojo.dto.base.LineDataDTO;
import com.wjj.sixinone.common.util.Result;
import com.wjj.sixinone.mapper.IndexMapper;
import com.wjj.sixinone.service.IndexService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class IndexServiceImpl implements IndexService {
    @Autowired
    private IndexMapper indexMapper;
    @Override
public Result dashboard() {
    Dashboard dashboard = new Dashboard();
    try {
        dashboard.setTotalBed(getSafeValue(indexMapper.selectTotalBed(), 0));
        dashboard.setTotalDoctor(getSafeValue(indexMapper.selectTotalDoctor(), 0));
        dashboard.setTotalPatient(getSafeValue(indexMapper.selectTotalPatient(), 0));
        dashboard.setTotalFreeBed(getSafeValue(indexMapper.selectTotalFreeBed(StatusEnum.NOT_USE.getMessage()), 0));
    } catch (Exception e) {
        System.err.println("Error while fetching dashboard data: " + e.getMessage());
        return Result.error(500, "Error while fetching dashboard data");
    }
    return Result.ok().put("data", dashboard);
}

    @Override
    public Result getLineChartData() {

        List<LineDataDTO> lineDatas = indexMapper.selectChartData();
        if (lineDatas == null || lineDatas.isEmpty()) {
            throw new GlobalException(ExceptionEnum.SELECT_ERROR);
        }

// 初始化数组
        String[] days = new String[lineDatas.size()];
        int[] counts = new int[lineDatas.size()];

// 遍历并填充数组
        for (int i = 0; i < lineDatas.size(); i++) {
            LineDataDTO lineData = lineDatas.get(i);
            days[i] = lineData.getDay();
            counts[i] = lineData.getCount();
        }

        return Result.ok().put("days",days).put("counts",counts);

    }

    @Override
    public Result getPieChartData() {
        List<PieDataDTO> pieDatas = indexMapper.patientInDepartment();
        return Result.ok().put("data",pieDatas);
    }

    /**
 * 一个安全的获取值的方法，如果输入为null，则返回默认值。
 * 这样可以避免空指针异常。
 *
 * @param value        可能为null的值
 * @param defaultValue 如果value为null，则返回的默认值
 * @return value或defaultValue，取决于value是否为null
 */
private static Integer getSafeValue(Integer value, int defaultValue) {
    return value != null ? value : defaultValue;
}


}
